/**
 * 
 */
package com.cn.daifaming.demoservice.sharding.algorithm;

import java.util.Collection;
import java.util.LinkedHashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;
import com.google.common.collect.Range;

/**
 * @author Administrator
 *
 */
public class MySingleKeyDatabaseShardingAlgorithm
		implements
			SingleKeyDatabaseShardingAlgorithm<String>
{
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MySingleKeyDatabaseShardingAlgorithm.class);
	/**
	 * sql 中关键字 匹配符为 =的时候，表的路由函数
	 */
	public String doEqualSharding(Collection<String> availableTargetNames,
			ShardingValue<String> shardingValue)
	{
		for (String each : availableTargetNames)
		{
			LOGGER.info("{},{},{}", each, shardingValue,
					shardingValue.getValue());
			String value = shardingValue.getValue();
			if (each.endsWith(Integer.valueOf(value) % 2 + ""))
			{
				return each;
			}
		}
		throw new IllegalArgumentException();
	}
	/**
	 * sql 中关键字 匹配符为 in 的时候，表的路由函数
	 */
	public Collection<String> doInSharding(
			Collection<String> availableTargetNames,
			ShardingValue<String> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<String>(
				availableTargetNames.size());
		for (String value : shardingValue.getValues())
		{
			for (String tableName : availableTargetNames)
			{
				if (tableName.endsWith(Integer.valueOf(value) % 2 + ""))
				{
					result.add(tableName);
				}
			}
		}
		return result;
	}
	/**
	 * sql 中关键字 匹配符为 between的时候，表的路由函数
	 */
	public Collection<String> doBetweenSharding(
			Collection<String> availableTargetNames,
			ShardingValue<String> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<String>(
				availableTargetNames.size());
		Range<String> range = (Range<String>) shardingValue.getValueRange();
		Integer lowerEndpoint = Integer.valueOf(range.lowerEndpoint());
		Integer upperEndpoint = Integer.valueOf(range.upperEndpoint());
		for (Integer i = lowerEndpoint; i <= upperEndpoint; i++)
		{
			for (String each : availableTargetNames)
			{
				if (each.endsWith(i % 2 + ""))
				{
					result.add(each);
				}
			}
		}
		return result;
	}
}
